package com.young.mylib;

import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Young on 2025/3/11.
 */
public class OKHttpClient extends Thread {
    private static final String TAG = "OKHttpClient";
    OkHttpClient okHttpClient;
    private static OKHttpClient mInstance;
    public static final String ACTION_OK_HTTP_RESP = "ACTION_OK_HTTP_RESP";//场景配置的消息到达

    public static OKHttpClient getInstance() {
        if (mInstance == null) {
            mInstance = new OKHttpClient();
        }
        return mInstance;
    }

    public OKHttpClient() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//与服务器建立连接的时长，默认10s
                .readTimeout(10, TimeUnit.SECONDS)//读取服务器返回数据的时长
                .writeTimeout(10, TimeUnit.SECONDS)//向服务器写入数据的时长，默认10s
                .retryOnConnectionFailure(true)//失败重连
                .followRedirects(false)//重定向
                .build();

    }

    /**
     * POST方式提交json
     */
    public void postJson(String url, String body, HttpCallback callback) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "POST FAIL");
                callback.onFail(url, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.onHttpResponse(url, response.body().string());

            }
        });
    }

}
